package com.jww.controller.store;

import com.github.pagehelper.PageInfo;
import com.jww.controller.BaseServlet;
import com.jww.domain.store.Catalog;
import com.jww.domain.store.Company;
import com.jww.domain.store.Question;
import com.jww.service.CatalogService;
import com.jww.service.CompanyService;
import com.jww.service.QuesTionService;
import com.jww.service.impl.CatalogServiceImpl;
import com.jww.service.impl.CompanyServiceImpl;
import com.jww.service.impl.QuesTionServiceImpl;
import com.jww.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {
    private QuesTionService service=new QuesTionServiceImpl();

    public void selectAll(HttpServletRequest req, HttpServletResponse resp){

        try {
            String pageNum = req.getParameter("pageNum");
            String pageSize = req.getParameter("pageSize");
            List<Question> list=service.selectAll(pageNum,pageSize);
            PageInfo<Question> info=new PageInfo<>(list);
            req.setAttribute("page",info);
            req.getRequestDispatcher("/pages/store/question/list.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void list(HttpServletRequest req, HttpServletResponse resp){

        try {

            CatalogService service=new CatalogServiceImpl();
            CompanyService service1=new CompanyServiceImpl();
            List<Catalog> catalogList = service.list();
            List<Company> companyList = service1.list();
            req.setAttribute("catalogList",catalogList);
            req.setAttribute("companyList",companyList);
            req.getRequestDispatcher("/pages/store/question/add.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void save(HttpServletRequest req, HttpServletResponse resp) {

        //确认该操作是否支持文件上传
        if (ServletFileUpload.isMultipartContent(req)) {
            try {
                //创建磁盘工厂对象
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //Servlet文件上传核心对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                //从req读取数据
                List<FileItem> fileItems = fileUpload.parseRequest(req);

                //创建一个标记位，标记当前位置是否有上传文件操作
                boolean flag=false;
                for (FileItem item:fileItems){
                    if (item.getName()!=null && !"".equals(item.getName())){
                        flag=true;
                        break;
                    }
                }
                //处理form表单提交的普通数据
                Question question = BeanUtil.fillBean(fileItems, Question.class);

                String pictureName = service.save(question,flag);
                //处理form表单提交的文件数据
                for (FileItem item : fileItems) {
                    //当前表单是否是文件表单
                    if (!item.isFormField()) {
                        //从临时文件的地上将内容写入到指定地方
                        item.write(new File(this.getServletContext().getRealPath("upload"), pictureName));
                    }
                }
                selectAll(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }
    public void delete(HttpServletRequest req, HttpServletResponse resp){
        String ids = req.getParameter("ids");
        boolean flag = service.delete(ids);

        if (flag){
            selectAll(req,resp);
        }else {
            try {
                req.getRequestDispatcher("pages/error.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void selectById(HttpServletRequest req, HttpServletResponse resp){


        try {
            String id = req.getParameter("id");
            Question question = service.selectById(id);
           /* List<Question> questionList = service.list();*/
            CatalogService service=new CatalogServiceImpl();
            CompanyService service1=new CompanyServiceImpl();

            List<Catalog> catalogList = service.list();
            List<Company> companyList = service1.list();

            req.setAttribute("catalogList",catalogList);
            req.setAttribute("companyList",companyList);
            req.setAttribute("question",question);
            req.getRequestDispatcher("/pages/store/question/update.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void update(HttpServletRequest req, HttpServletResponse resp){

        //确认该操作是否支持文件上传
        if (ServletFileUpload.isMultipartContent(req)) {
            try {
                //创建磁盘工厂对象
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //Servlet文件上传核心对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                //从req读取数据
                List<FileItem> fileItems = fileUpload.parseRequest(req);

                //创建一个标记位，标记当前位置是否有上传文件操作
                boolean flag=false;
                for (FileItem item:fileItems){
                    if (item.getName()!=null && !item.getName().equals("")){
                        flag=true;
                        break;
                    }
                }

                //处理form表单提交的普通数据
                Question question = BeanUtil.fillBean(fileItems, Question.class);

                service.update(question,flag);

                //处理form表单提交的文件数据
                for (FileItem item : fileItems) {
                    //当前表单是否是文件表单
                    if (!item.isFormField()) {
                        //从临时文件的地上将内容写入到指定地方
                        item.write(new File(this.getServletContext().getRealPath("upload"), question.getId()));
                    }
                }
                selectAll(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    public void toUpload(HttpServletRequest req, HttpServletResponse resp){
        try {
            req.getRequestDispatcher("/pages/store/question/testFileUpload.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void testUpload(HttpServletRequest req, HttpServletResponse resp){
        //确认该操作是否支持文件上传
        if (ServletFileUpload.isMultipartContent(req)){
            try {
                //创建磁盘工厂对象
                DiskFileItemFactory factory=new DiskFileItemFactory();
                //Servlet文件上传核心对象
                ServletFileUpload fileUpload = new ServletFileUpload(factory);
                //从req读取数据
                List<FileItem> fileItems = fileUpload.parseRequest(req);
                for (FileItem item:fileItems){
                    //当前表单是否是文件表单
                    if (!item.isFormField()){
                        //从临时文件的地上将内容写入到指定地方
                        item.write(new File(this.getServletContext().getRealPath("upload"),item.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void importTest(HttpServletRequest req, HttpServletResponse resp){

        try {
            //设置返回数据类型为xlsx文件
            resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            //设置文件名
            String fileName=new String("测试文件名.xlsx".getBytes(),"iso-8859-1");
            resp.addHeader("Content-Disposition","attachment;fileName="+fileName);

            //获取存取数据的字节数组输出字节流
            ByteArrayOutputStream os=service.uploadReport();
            //获取产生响应的流对象
            ServletOutputStream ous = resp.getOutputStream();
            //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
            os.writeTo(ous);
            //将输出流刷新 关闭流
            ous.flush();
            os.close();

            selectAll(req,resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
